<template>
	<s-layout title="购物车" tabbar="/pages/index/cart" :bgStyle="{ color: '#f9f9f9' }">
		<s-empty v-if="state.list.length === 0" text="购物车空空如也,快去逛逛吧~" icon="/static/cart-empty.png" />

		<!-- 头部 -->
		<view class="cart-box ss-flex ss-flex-col ss-row-between" v-if="state.list.length">
			<view class="cart-header ss-flex ss-col-center ss-row-between ss-p-x-30">
				<view class="header-left ss-flex ss-col-center ss-font-28">

					<text class="goods-number ss-flex">购物数量{{ state.list.length }}</text>
					件
				</view>
				<view class="header-right">
					<button v-if="state.editMode" class="ss-reset-button" @tap="state.editMode = false">
						取消
					</button>
					<button v-else class="ss-reset-button right" @tap="state.editMode = true">
						编辑
					</button>
				</view>
			</view>
			<!-- 内容 -->
			<view class="cart-content ss-flex-1 ss-p-x-10 ss-m-b-40">
				<view class="goods-box ss-r-10 ss-m-b-20" v-for="item in state.list" :key="item.id">
					<view class="ss-flex ss-col-center">
						<label class="check-box ss-flex ss-col-center ss-p-l-10" @tap="onSelectSingle(item.id)">
							<radio :checked="state.selectedIds.includes(item.id)" color="#f27020"
								style="transform: scale(0.8)" @tap.stop="onSelectSingle(item.id)" />
						</label>
						<s-goods-item :title="item.goods.title" :img="item.sku_price.image || item.goods.image"
							:price="item.sku_price.price" :skuText="item.sku_price.goods_sku_text" priceColor="#FF3000"
							:titleWidth="430">
							<template v-if="!state.editMode" v-slot:tool>
								<su-number-box :min="0" :max="item.sku_price.stock" :step="1" v-model="item.goods_num"
									@change="onNumberChange($event, item)"></su-number-box>
							</template>
						</s-goods-item>
					</view>
				</view>
			</view>
			<!-- 底部 -->
			<su-fixed bottom :val="48" placeholder v-if="state.list.length > 0" :isInset="false">
				<view class="cart-footer ss-flex ss-col-center ss-row-between ss-p-x-30 border-bottom ss-m-b-10">
					<view class="footer-left ss-flex ss-col-center">
						<label class="check-box ss-flex ss-col-center ss-p-r-30" @tap="onSelectAll">
							<radio :checked="state.isAllSelected" color="#f27020" style="transform: scale(0.8)"
								@tap.stop="onSelectAll" />
							<view class="ss-m-l-8"> 全选 </view>
						</label>

					</view>
					<view class="footer-right ss-flex">
						<text>合计：</text>
						<view class="text-price price-text">
							{{ state.totalPriceSelected }}
						</view>
						<button v-if="state.editMode" class="ss-reset-button pay-btn" @tap="onDelete">
							删除
						</button>
						<button v-else class="ss-reset-button pay-btn" @tap="toRead">
							立即下单
							{{ state.selectedIds?.length ? `(${state.selectedIds.length})` : '' }}
						</button>
					</view>
				</view>
			</su-fixed>
		</view>
		<su-popup :show="state.showRead" type="center" round="10" :isMaskClick="false">
			<view class="model-box ss-flex-col">
				<view class="score-title ss-p-t-26">{{state.title}}</view>
				<scroll-view scroll-y="true" class="model-bg ss-flex-col ss-col-center ss-row-right"
					scroll-with-animation="true">
					<view class="title ss-m-x-20"><mp-html class="richtext" :content="state.content"></mp-html>
					</view>
				</scroll-view>
				<view class="ss-flex ss-col-center but_box ss-p-x-40 ss-p-y-16">
					<button class="ss-reset-button cancel-btn" @tap="state.showRead = false">取消</button>
					<button class="ss-reset-button confirm-btn" @tap="onSure">确认</button>
				</view>
			</view>
		</su-popup>
	</s-layout>
</template>

<script setup>
	import sheep from '@/sheep';
	import {
		computed,
		reactive,
		unref
	} from 'vue';
	import dayjs from 'dayjs';

	const sys_navBar = sheep.$platform.navbar;
	const cart = sheep.$store('cart');

	const state = reactive({
		title: '',
		content: '',
		showRead: false,
		editMode: false,
		list: computed(() => cart.list),
		selectedList: [],
		selectedIds: computed(() => cart.selectedIds),
		isAllSelected: computed(() => cart.isAllSelected),
		totalPriceSelected: computed(() => cart.totalPriceSelected),
		timeFirst: '',
		timeSecond: ''
	});

	// 单选选中
	function onSelectSingle(id) {
		cart.selectSingle(id);
	}
	// 全选
	function onSelectAll() {
		cart.selectAll(!state.isAllSelected);
	}

	async function toRead() {
		state.timeFirst = dayjs().format('YYYY-MM-DD HH:mm:ss');
		let res = await sheep.$api.user.profile();

		if (res.code == 1) {
			if (res.data.pay_after_notice == 1) {
				onConfirm()
				return
			}

			let {
				data,
				code
			} = await sheep.$api.app.init();

			if (code == 1) {
				let pay_after_notice = data.app.pay_after_notice
				state.title = data.app.pay_after_notice.title;

				const res = await sheep.$api.data.richtext(pay_after_notice.id);

				if (res.code === 1) {
					state.showRead = true
					state.content = res.data.content;
				}
			}
		}
	}

	async function onSure() {
		state.timeSecond = dayjs().format('YYYY-MM-DD HH:mm:ss');
		// console.log(state.timeFirst,state.timeSecond, 'timeSecond', GetDateDiff(state.timeFirst,state.timeSecond,'second'))
		if(GetDateDiff(state.timeFirst,state.timeSecond,'second')<3){
			uni.showToast({
				title:'请先阅读协议',
				icon:'none'
			})
			state.timeFirst = dayjs().format('YYYY-MM-DD HH:mm:ss');
			return
		}
		const {
			code,
			data
		} = await sheep.$api.user.payAfterNotice();

		if (code == 1) {
			state.showRead = false
		}
	}

	function GetDateDiff(startTime, endTime, diffType) {
		//将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
		startTime = startTime.replace(/\-/g, "/");
		endTime = endTime.replace(/\-/g, "/");
		//将计算间隔类性字符转换为小写
		diffType = diffType.toLowerCase();
		var sTime = new Date(startTime); //开始时间
		var eTime = new Date(endTime); //结束时间
		//作为除数的数字
		var timeType = 1;
		switch (diffType) {
			case "second":
				timeType = 1000;
				break;
			case "minute":
				timeType = 1000 * 60;
				break;
			case "hour":
				timeType = 1000 * 3600;
				break;
			case "day":
				timeType = 1000 * 3600 * 24;
				break;
			default:
				break;
		}
		return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType));
	}
	// 结算
	function onConfirm() {
		let goods_list = [];
		state.selectedList = state.list.filter((item) => state.selectedIds.includes(item.id));
		state.selectedList.map((item) => {
			goods_list.push({
				goods_id: item.goods_id,
				goods_num: item.goods_num,
				goods_sku_price_id: item.goods_sku_price_id,
			});
		});
		if (goods_list.length === 0) {
			sheep.$helper.toast('请选择商品');
			return;
		}
		sheep.$router.go('/pages/order/confirm', {
			data: JSON.stringify({
				order_type: 'goods',
				goods_list,
				from: 'cart',
			}),
		});
	}

	function onNumberChange(e, cartItem) {
		if (e === 0) {
			cart.delete(cartItem.id);
			return;
		}
		if (cartItem.goods_num === e) return;
		cartItem.goods_num = e;
		cart.update({
			goods_id: cartItem.goods_id,
			goods_num: e,
			goods_sku_price_id: cartItem.goods_sku_price_id,
		});
	}
	async function onDelete() {
		cart.delete(state.selectedIds);
	}
</script>

<style lang="scss" scoped>
	:deep(.ui-fixed) {
		height: 72rpx;
	}

	.model-box {
		width: 520rpx;
		height: 60vh;
		background: #fff;
		overflow-y: scroll;

		.model-content {
			height: 56vh;
		}

		.richtext {
			width: 100%;
			height: 50vh;
			font-size: 24rpx;
			font-weight: 500;
			color: #999999;
			margin: 20rpx 0 0 0;
			padding-bottom: 60rpx;
		}

		.cicon-check-round {
			font-size: 70rpx;
			color: #fff;
		}

		.score-title {
			position: sticky;
			background: #fff;
			width: 520rpx;
			text-align: center;
			top: 0;
			height: 56rpx;
			font-size: 34rpx;
			font-family: OPPOSANS;
			font-weight: 500;
			color: #000;
			text-align: center;
			z-index: 1000
		}

		.model-title {
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
		}

		.but_box {
			position: sticky;
			background: #fff;
			width: 440rpx;
			text-align: center;
			z-index: 1000;
			top: 82%;
			height: 80rpx;
		}

		.cancel-btn {
			width: 220rpx;
			height: 66rpx;
			border: 2rpx solid #ff6000;
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #ff6000;
			line-height: normal;
			margin-right: 10rpx;
		}

		.confirm-btn {
			width: 220rpx;
			height: 66rpx;
			background: linear-gradient(90deg, #ff6000, #fe832a);
			box-shadow: 0 0.2em 0.5em rgba(#ff6000, 0.4);
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
			line-height: normal;
		}

		.model-bg {
			height: 82%;
		}
	}

	.cart-box {
		width: 100%;

		.cart-header {
			height: 70rpx;
			background-color: #fff;
			width: 100%;
			position: fixed;
			left: 0;
			top: v-bind('sys_navBar') rpx;
			z-index: 1000;
			box-sizing: border-box;

		}

		.right {
			color: #f27020;
		}

		.cart-footer {
			height: 100rpx;
			background-color: #fff;

			.pay-btn {
				width: 230rpx;
				height: 70rpx;
				font-size: 28rpx;
				line-height: 28rpx;
				font-weight: 500;
				border-radius: 40rpx;
				background: linear-gradient(90deg, #f99a4e, #e84f1e) !important;
				color: var(--ui-BG-Main-TC) !important;
			}

			.text-price {
				color: #e84f1e;
				margin-right: 20rpx;
				font-size: 32rpx;
			}

		}

		.cart-content {
			margin-top: 90rpx;
			width: 94%;

			.goods-box {
				background-color: #fff;
			}
		}
	}
</style>